package com.jvmoutofmemory.platform.pushutil.task;

import com.google.common.collect.Lists;
import com.jvmoutofmemory.platform.pushutil.entity.PushJob;
import com.jvmoutofmemory.platform.pushutil.service.PushJobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.UUID;

/**
 * 定时推送请求 Created by wq on 2017/5/24.
 */
public class PushTaskJob {
    private static final Logger logger = LoggerFactory.getLogger(PushTaskJob.class);

    /**
     * 每次job执行，推送 未推送的数据的数量
     */
    @Value("${push.pushNotPushedSize:5}")
    private int pushNotPushedSize;
    /**
     * 每次job执行，推送 推送失败 的数据的数量
     */
    @Value("${push.pushFailedSize:5}")
    private int pushFailedSize;

    @Autowired
    private PushJobService pushJobService;

    public void push() {
        MDC.put("traceId", UUID.randomUUID().toString().replace("-", ""));
        logger.info("--------定时推送开始--------");
        List<PushJob> pushJobs = Lists.newArrayList();
        pushJobs.addAll(pushJobService.selectNotPushedPushJobList(pushNotPushedSize));
        pushJobs.addAll(pushJobService.selectFailedPushJobList(pushFailedSize));

        if (CollectionUtils.isEmpty(pushJobs)) {
            logger.info("没有要推送的任务。");
            return;
        }

        doPush(pushJobs);
        logger.info("--------定时推送结束--------");
    }

    /**
     * 删除已经完成的数据
     * @param days 保留最近N天数据
     */
    public void deleteFinishedData(int days) {
        MDC.put("traceId", UUID.randomUUID().toString().replace("-", ""));
        logger.info("-----删除已完成的数据，保留天数: {}------",days);
        List<Long> ids = pushJobService.selectFinishData(days);
        if (CollectionUtils.isEmpty(ids)) {
            logger.error("No finished data found before date : {}", days);
            return;
        }

        ids.forEach(id -> {
            pushJobService.deleteById(id);
        });
        logger.info("-----删除已完成的数据完成，共删除: {}------", ids.size());
    }


    private void doPush(List<PushJob> pushJobs) {
        for (PushJob pushJob : pushJobs) {
            try {
                pushJobService.push(pushJob);
            } catch (Exception e) {
                logger.error(String.format("推送请求发送失败:  %s  %s", pushJob.getRequestId(), pushJob.getUrl()), e);
                logger.error(e.getMessage(), e);
            }
        }
    }
}
